<?php
/*
 * @Author: lokei
 * @Date: 2022-09-12 00:02:07
 * @LastEditors: lokei
 * @LastEditTime: 2023-07-25 17:37:59
 * @Description: 
 */

namespace App\Http\Controllers\Store\Store;

use App\Common\Permission\RoleGuard;
use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Scrm\Clerk\ClerkModel;
use App\Models\Store\StoreModel;
use Illuminate\Http\Request;

use OpenApi\Annotations\Get;
use OpenApi\Annotations\MediaType;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\RequestBody;
use OpenApi\Annotations\Header;
use OpenApi\Annotations\Response;
use OpenApi\Annotations\Schema;
use App\Http\Responses\CommResp;
use App\Middle\StatisticMiddle;
use App\Models\Clerk\ClerkModel as ClerkClerkModel;
use App\Models\Pay\Card\PayCardModel;
use App\Models\Store\ConfModel;

class StoreController extends Controller
{
    /**
     * @Get(
     *     path="/api/store/list",
     *     tags={"【商家】商家管理"},
     *     summary="商家列表",
     *     @Response(
     *         response="200",
     *         description="正常操作响应",
     *         @MediaType(
     *             mediaType="application/json",
     *             @Schema(
     *                 allOf={
     *                     @Schema(ref="#/components/schemas/CommResp")
     *                 }
     *             )
     *         )
     *     )
     * )
     *
     * @param Request $request
     *
     * @return CommResp
     */
    public function list(Request $request)
    {
        $res = ResultTool::success();
        $model = RoleGuard::store_guard(null, 'App\Models\Store\StoreModel', 'id');
        if (!is_null($request->input('searching_store_key')) && $request->input('searching_store_key') != '') {
            if (is_null($model)) {
                $model = StoreModel::select([
                    'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                ])->where('name', 'LIKE', "%{$request->input('searching_store_key')}%");
            } else {
                $model = $model->select([
                    'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                ])->where('name', 'LIKE', "%{$request->input('searching_store_key')}%");
            }
        } else if (!is_null($request->input('mode')) && $request->input('mode') == 'recommend') {
            $store_conf = ConfModel::first();
            $ids = explode(';', $store_conf->recommend_stores);
            $model = StoreModel::select([
                'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
            ])->whereIn('id', $ids);
            if (!is_null($request->input('tag_id')) && intval($request->input('tag_id')) > 0) {
                $like1 = $request->input('tag_id');
                $model->where('tags', '=', $like1);
                $like2 = $request->input('tag_id') . '|';
                $model->orWhere('tags', 'LIKE', $like2 . "%");
                $like3 = '|' . $request->input('tag_id');
                $model->orWhere('tags', 'LIKE', "%" . $like3);
                $like4 = '|' . $request->input('tag_id') . '|';
                $model->orWhere('tags', 'LIKE', "%" . $like4 . "%");
            }
        } else if (!is_null($request->input('mode')) && $request->input('mode') == 'pay_card') {
            $card = PayCardModel::where('id', '=', $request->input('card_id'))->first();
            $store_ids = [];
            array_push($store_ids, $card->store_id);
            $model = StoreModel::select([
                'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
            ])->whereIn('id', $store_ids);
        } else {
            if ($request->input('tag_id') != null && $request->input('tag_id') > 0) {
                if ($request->input('status') != null && $request->input('status') != '') {
                    if (is_null($model)) {
                        $model = StoreModel::where('status', '=', $request->input('status'))->where('tags', '=', $request->input('tag_id'))->orWhere('tags', 'LIKE', "%{$request->input('tag_id')}|%")->orWhere('tags', 'LIKE', "%|{$request->input('tag_id')}%")->select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    } else {
                        $model = $model->where('status', '=', $request->input('status'))->where('tags', '=', $request->input('tag_id'))->orWhere('tags', 'LIKE', "%{$request->input('tag_id')}|%")->orWhere('tags', 'LIKE', "%|{$request->input('tag_id')}%")->select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    }
                } else {
                    if (is_null($model)) {
                        $model = StoreModel::where('tags', '=', $request->input('tag_id'))->orWhere('tags', 'LIKE', "%{$request->input('tag_id')}|%")->orWhere('tags', 'LIKE', "%|{$request->input('tag_id')}%")->select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    } else {
                        $model = $model->where('tags', '=', $request->input('tag_id'))->orWhere('tags', 'LIKE', "%{$request->input('tag_id')}|%")->orWhere('tags', 'LIKE', "%|{$request->input('tag_id')}%")->select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    }
                }
            } else {
                if ($request->input('status') != null && $request->input('status') != '') {
                    if (is_null($model)) {
                        $model = StoreModel::where('status', '=', $request->input('status'))->select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    } else {
                        $model = $model->where('status', '=', $request->input('status'))->select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    }
                } else {
                    if (is_null($model)) {
                        $model = StoreModel::select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    } else {
                        $model = $model->select([
                            'id', 'order_index', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'detail', 'tags', 'status'
                        ]);
                    }
                }
            }
        }
        if ($request->input('order') != null) {
            if ($request->input('order') == '-pv') {
                $model = $model->orderBy('pv', 'desc');
            }
        } else {
            $model = $model->orderBy('order_index', 'desc');
        }
        $items = $model->get();
        $res['data']['items'] = $items;
        $res['data']['total'] = count($items);
        return $res;
    }

    public function ofIds(Request $request)
    {
        $res = ResultTool::success();
        $ids_str = $request->input('ids');
        $ids = json_decode($ids_str);
        $items = StoreModel::whereIn('id', $ids)->select([
            'id', 'uid', 'name', 'name_en', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'intro', 'detail'
        ])->orderBy('order_index', 'desc')->get();
        $res['data']['items'] = $items;
        $res['data']['total'] = count($items);
        return $res;
    }

    /**
     * @Get(
     *     path="/api/store/get",
     *     tags={"【商家】商家管理"},
     *     summary="获取商家",
     *     @OA\Parameter(
     *         name="id",
     *         in="query",
     *         required=true,
     *         @OA\Schema(
     *             type="integer"
     *         )
     *     ),
     *     @Response(
     *         response="200",
     *         description="正常操作响应",
     *         @MediaType(
     *             mediaType="application/json",
     *             @Schema(
     *                 allOf={
     *                     @Schema(ref="#/components/schemas/CommResp")
     *                 }
     *             )
     *         )
     *     )
     * )
     *
     * @param Request $request
     *
     * @return CommResp
     */
    public function get(Request $request)
    {
        $store = StoreModel::where('id', '=', $request->input('id'))->select([
            'id', 'uid', 'name', 'name_en', 'types', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city',
            'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'intro', 'detail',
            'income', 'withdrawed', 'withdrawing', 'business_category', 'pv', 'product_count', 'collect_count', 'credit_certificated', 'credit_level_id', 'business_status'
        ])->first();
        $res = ResultTool::success();
        $res['data'] = $store;
        return $res;
    }

    public function ofMe()
    {
        $user = app('auth')->user();
        $store = StoreModel::where('uid', '=', $user->uid)->select([
            'id', 'uid', 'name', 'name_en', 'types', 'img_thumb', 'app_mode', 'index_mode', 'img_display', 'gallery', 'prov', 'city', 'district', 'address', 'contacts_name', 'contacts_mobile', 'contacts_email', 'lng', 'lat', 'tips', 'intro', 'detail', 'income', 'withdrawed', 'withdrawing', 'business_category', 'business_status', 'status'
        ])->first();
        $res = ResultTool::success();
        $res['data'] = $store;
        return $res;
    }

    public function statusOfMe()
    {
        $user = app('auth')->user();
        $store = StoreModel::where('uid', '=', $user->uid)->select(['status'])->first();
        $res = ResultTool::success();
        if (!is_null($store)) {
            $res['data']['status'] = $store->status;
        } else {
            $res['data']['status'] = '';
        }
        return $res;
    }

    public function roleOfMe()
    {
        $user = app('auth')->user();
        $store_id = 0;
        $roles = '';
        $store = StoreModel::where('uid', '=', $user->uid)->first();
        if (!is_null($store)) {
            $roles = 'owner';
            $store_id = $store->id;
        }
        $clerk = ClerkClerkModel::where('uid', '=', $user->uid)->first();
        if (!is_null($clerk)) {
            if (!($store_id > 0)) {
                $store_id = $clerk->store_id;
            }
            if (!($roles == '')) {
                $roles .= '|';
            }
            $roles .= $clerk->role;
        }
        $res = ResultTool::success();
        if ($store_id > 0) {
            $res['data'] = [
                'store_id' => $store_id,
                'roles' => $roles
            ];
        }
        return $res;
    }

    // /**
    //  * @Post(
    //  *     path="/api/store/update",
    //  *     tags={"演示"},
    //  *     summary="演示API",
    //  *     @RequestBody(
    //  *         @MediaType(
    //  *             mediaType="application/json",
    //  *             @Schema(
    //  *                 required={"name", "age"},
    //  *                 @Property(property="name", type="string", description="姓名"),
    //  *                 @Property(property="age", type="integer", description="年龄"),
    //  *                 @Property(property="gender", type="string", description="性别")
    //  *             )
    //  *         )
    //  *     ),
    //  *     @Response(
    //  *         response="200",
    //  *         description="正常操作响应",
    //  *         @MediaType(
    //  *             mediaType="application/json",
    //  *             @Schema(
    //  *                 allOf={
    //  *                     @Schema(ref="#/components/schemas/ApiResponse"),
    //  *                     @Schema(
    //  *                         type="object",
    //  *                         @Property(property="data", ref="#/components/schemas/CommResp")
    //  *                     )
    //  *                 }
    //  *             )
    //  *         )
    //  *     )
    //  * )
    //  *
    //  * @param Request $request
    //  *
    //  * @return CommResp
    //  */
    public function update(Request $request)
    {
        $store = StoreModel::where('id', '=', $request->input('id'))->first();
        $store->name = $request->input('name');
        if ($request->input('types') != null) {
            $store->types = $request->input('types');
        }
        $store->img_thumb = $request->input('img_thumb');
        $store->img_display = $request->input('img_display');
        $store->gallery = $request->input('gallery');
        $store->prov = $request->input('prov');
        $store->city = $request->input('city');
        $store->district = $request->input('district');
        $store->address = $request->input('address');
        $store->contacts_name = $request->input('contacts_name');
        $store->contacts_mobile = $request->input('contacts_mobile');
        if ($request->input('lng') != null && $request->input('lng') != 'null' && $request->input('lng') != '') {
            $store->lng = $request->input('lng');
        }
        if ($request->input('lat') != null && $request->input('lat') != 'null' && $request->input('lat') != '') {
            $store->lat = $request->input('lat');
        }
        $store->tips = $request->input('tips');
        if ($request->input('intro') != null) {
            $store->intro = $request->input('intro');
        }
        $store->detail = $request->input('detail');
        if ($request->input('business_category') != null) {
            $store->business_category = $request->input('business_category');
        }
        $store->save();
        return ResultTool::success();
    }

    public function create(Request $request)
    {
        $store = new StoreModel();
        $store->name = $request->input('name');
        if ($request->input('types') != null) {
            $store->types = $request->input('types');
        }
        $store->img_thumb = $request->input('img_thumb');
        $store->img_display = $request->input('img_display');
        $store->gallery = $request->input('gallery');
        $store->prov = $request->input('prov');
        $store->city = $request->input('city');
        $store->district = $request->input('district');
        $store->address = $request->input('address');
        $store->contacts_name = $request->input('contacts_name');
        $store->contacts_mobile = $request->input('contacts_mobile');
        if ($request->input('lng') != null && $request->input('lng') != 'null' && $request->input('lng') != '') {
            $store->lng = $request->input('lng');
        }
        if ($request->input('lat') != null && $request->input('lat') != 'null' && $request->input('lat') != '') {
            $store->lat = $request->input('lat');
        }
        $store->tips = $request->input('tips');
        if ($request->input('intro') != null) {
            $store->intro = $request->input('intro');
        }
        if ($request->input('business_category') != null) {
            $store->business_category = $request->input('business_category');
        }
        // $store->detail = $request->input('detail');
        $store->save();

        StatisticMiddle::incStoreAmount(1);

        return ResultTool::success();
    }

    public function register(Request $request)
    {
        $user = app('auth')->user();
        $store = new StoreModel();
        $store->uid = $user->uid;
        $store->name = $request->input('name');
        if ($request->input('types') != null) {
            $store->types = $request->input('types');
        }
        $store->img_thumb = $request->input('img_thumb');
        $store->img_display = $request->input('img_display');
        $store->gallery = $request->input('gallery');
        $store->prov = $request->input('prov');
        $store->city = $request->input('city');
        $store->district = $request->input('district');
        $store->address = $request->input('address');
        $store->contacts_mobile = $request->input('contacts_mobile');
        if ($request->input('lng') != null && $request->input('lng') != 'null' && $request->input('lng') != '') {
            $store->lng = $request->input('lng');
        }
        if ($request->input('lat') != null && $request->input('lat') != 'null' && $request->input('lat') != '') {
            $store->lat = $request->input('lat');
        }
        $store->tips = $request->input('tips');
        if ($request->input('intro') != null) {
            $store->intro = $request->input('intro');
        }
        if ($request->input('business_category') != null) {
            $store->business_category = $request->input('business_category');
        }
        // $store->detail = $request->input('detail');
        $store->save();

        StatisticMiddle::incStoreAmount(1);

        return ResultTool::success();
    }

    public function delete(Request $request)
    {
        StoreModel::where('id', '=', $request->input('id'))->delete();
        return ResultTool::success();
    }

    public function setOrder(Request $request)
    {
        $store = StoreModel::where('id', '=', $request->input('store_id'))->first();
        $store->order_index = $request->input('order_index');
        $store->save();
        return ResultTool::success();
    }
}
